import { forEachRecursively } from '@/utils/array-recursion'
import type { RouteRecordRaw } from 'vue-router';
import type { RouteMetaMore } from '@/types/router-menu'
export type ChildAppRouteInfo = {
    path: string
    name: string
    meta: RouteMetaMore
}

export function buildChildAppRoutes(routes: RouteRecordRaw[], resolve: (appName: string, childAppRoutes: ChildAppRouteInfo[]) => void) {
    const allRoutes: Record<string, RouteRecordRaw[]> = {}
    forEachRecursively(routes, (route: RouteRecordRaw) => {
        if (route.props) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const appName: string = (route.props as Record<string, any>)['groupCode']
            let appRoutes = allRoutes[appName]
            if (!appRoutes) {
                appRoutes = []
                allRoutes[appName] = appRoutes
            }
            appRoutes.push(route)
        }

    })

    Object.keys(allRoutes).forEach(appName => {
        const appRoutes = allRoutes[appName]
        const appRoutesData = appRoutes.map((route => {
            const meta: RouteMetaMore | undefined = route.meta
            return {
                // path: '/' + route.groupCode + route.url,
                path: meta!.url!,
                name: (route.name as string).replace(appName, ''),
                meta: meta!
                // pagePath: route.pagePath
            }
        }))

        resolve(appName, appRoutesData)
    })
}